package lock;

import sun.security.krb5.internal.Ticket;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author yyh
 * @create 2020-11-09 15:27
 *                  Lock
 */
public class SaleTicketDemo02 {

    private static Lock lock = new ReentrantLock();

    public static void main(String[] args) {

        Ticket2 t = new Ticket2();
        new Thread(() -> {
            for (int i = 0; i < 30; i++) {
                t.sale();
            }
        },"A").start();

        new Thread(() -> {
            for (int i = 0; i < 30; i++) {
                t.sale();
            }
        },"B").start();


    }

    private static class Ticket2{

        private int num = 30;

        private int i = 0;

        public void sale(){

            lock.lock();

            try {
                if(num > 0){
                    System.out.println(Thread.currentThread().getName() + "卖出了" + (++i) + "张票，还剩余： " + (--num) + "张");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally{
                lock.unlock();
            }



        }
    }


}
